/*
 * Copyright © 2018 CODESTD.COM Inc. All rights reserved.
 */
package com.codestd.security.shiro;

import com.codestd.security.model.SysUser;
import com.codestd.security.shiro.jwt.JwtTokenManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.apache.shiro.web.subject.WebSubjectContext;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 创建Subject
 *
 * @author jaune
 * @since 1.0.0
 */
public class StatelessWebSubjectFactory extends DefaultWebSubjectFactory {

    public static final String AUTH_HEADER_NAME = "AUTHENTICATION";

    private JwtTokenManager jwtTokenManager;

    public void setJwtTokenManager(JwtTokenManager jwtTokenManager) {
        this.jwtTokenManager = jwtTokenManager;
    }

    @Override
    public Subject createSubject(SubjectContext context) {
        context.setSessionCreationEnabled(false);
        if (!(context instanceof WebSubjectContext)) {
            return super.createSubject(context);
        }
        WebSubjectContext wsc = (WebSubjectContext) context;

        HttpServletRequest request = WebUtils.toHttp(wsc.resolveServletRequest());
        String token = request.getHeader(AUTH_HEADER_NAME);
        if (this.jwtTokenManager.checkToken(token)) {
            SysUser user = this.jwtTokenManager.resolve(token);
            wsc.setAuthenticated(true);
            wsc.setPrincipals(new SimplePrincipalCollection(user, user.getUsername()));
            this.refreshToken(token);
        }
        return super.createSubject(context);
    }

    private void refreshToken(String token) {
        this.jwtTokenManager.refreshToken(token);
    }
}
